﻿using AutoMapper;
using MediatR;
using Traceability.API.Applications.Command.AquacultureCommand;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.Applications.CommandHandler.AquacultureCommandHandler
{
    public class AquacultureAddCommandHandler : IRequestHandler<AquacultureAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Aquaculture_Information> aquacultureRepository;
        private readonly IMapper mapper;

        public AquacultureAddCommandHandler(IBaseRepository<Aquaculture_Information> aquacultureRepository, IMapper mapper)
        {
            this.aquacultureRepository = aquacultureRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(AquacultureAddCommand request, CancellationToken cancellationToken)
        {
            var model= mapper.Map<Aquaculture_Information>(request);
            if (request.Id != 0)
            {
                model.UpDataUserId = request.CreateUserId;
                model.UpDataTime = DateTime.Now;
            }
            var count=await aquacultureRepository.Update(model);
            APIResult<int> aPIResult = new APIResult<int>();
            if (count > 0)
            {
                aPIResult.Code=EnumCode.Ok;
                aPIResult.Msg = "保存成功";
                aPIResult.Data = count;
            }
            else
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Msg = "保存失败";
                aPIResult.Data = count;
            }
            return await Task.FromResult(aPIResult);
            
        }
    }
}
